use base_any::tables::ALL;
use html::Textarea;
use leptos::*;

#[component]
pub fn App() -> impl IntoView {
    let input = create_node_ref::<Textarea>();
    let (output, set_output) = create_signal(String::new());
    let (table, set_table) = create_signal("BASE1024".to_owned());

    let get_input = move || input.get().unwrap().value();
    let get_table = move || {
        let name = table.get();
        ALL.iter().find(|x| x.0 == name).unwrap().1
    };
    let encode = move |_| {
        set_output.set(get_table().encode_str(get_input().bytes()));
    };
    let decode = move |_| match get_table().decode_vec(get_input().chars()) {
        Ok(data) => {
            let data = String::from_utf8(data)
                .unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned());
            set_output.set(data);
        }
        Err(ch) => set_output.set(format!("错误，无法解析字符：{ch}")),
    };

    view! {
        <textarea placeholder="请输入" node_ref=input></textarea>
        <hr />
        <button type="button" on:click=encode>编码</button>
        <button type="button" on:click=decode>解码</button>
        <select
            on:change=move |ev| set_table.set(event_target_value(&ev))
            prop:value=table
        >
            {ALL.iter().map(|&(name, _)| view! {
                <option value=name>{name}</option>
            }).collect_view()}
        </select>
        <hr />
        <textarea placeholder="输出……" readonly prop:value=output></textarea>
    }
}
